1.File System

CommonJS (CJS) vs. ECMAScript Modules (ESM)

CommonJS Syntax

File System Operations

Using the fs module, you can perform various file operations:

  1. Write to a File:

    fs.writeFile('hey.txt', "helloworld", function(err) {
        if (err) console.error(err);
        else console.log("File written successfully.");
    });
    
  2. Append to a File:

    fs.appendFile("hey.txt", " this is new", function(err) {
        if (err) console.error(err);
        else console.log("Content appended successfully.");
    });
    
  3. Rename a File:

    fs.rename("hey.txt", "hello.txt", function(err) {
        if (err) console.error(err);
        else console.log("File renamed successfully.");
    });
    
  4. Copy a File:

    • To copy a file, you can use fs.copyFile (Node.js 8.5.0 and above):
    fs.copyFile('source.txt', 'destination.txt', (err) => {
        if (err) console.error(err);
        else console.log('File copied successfully.');
    });
    
  5. Delete a File (Unlink):

    fs.unlink("hello.txt", function(err) {
        if (err) console.error(err);
        else console.log("File deleted successfully.");
    });
    

6. Delete a Directory


7. Create a Folder


8. Read a File


9. Read Folder Contents